package com.ruoyi.feike.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.StatusReturnCodeConstant;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.msg.ObjectRestResponse;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.config.OutRequest;
import com.ruoyi.feike.domain.ApprovedLimitAndCondition;
import com.ruoyi.feike.domain.DealerInformation;
import com.ruoyi.feike.domain.vo.ThirdCreditInfoSimpleChild;
import com.ruoyi.feike.domain.vo.ThirdCreditInfoSimpleVO;
import com.ruoyi.feike.domain.vo.ThirdCreditInfoVO;
import com.ruoyi.feike.mapper.DealerInformationMapper;
import com.ruoyi.feike.service.IAnnualReviewyService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.feike.mapper.CreditConditionMapper;
import com.ruoyi.feike.domain.CreditCondition;
import com.ruoyi.feike.service.ICreditConditionService;
import org.springframework.web.client.RestTemplate;

/**
 * feikeService业务层处理
 *
 * @author ybw
 * @date 2022-07-12
 */
@Slf4j
@Service
public class
CreditConditionServiceImpl implements ICreditConditionService
{
    @Autowired
    private CreditConditionMapper creditConditionMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Value("${wfs.url}")
    private String wfsUrl;

    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public CreditCondition selectCreditConditionById(String id)
    {
        return creditConditionMapper.selectCreditConditionById(id);
    }

    /**
     * 查询feike列表
     *
     * @param dealerNames feike
     * @return feike
     */
    @Override
    public List<CreditCondition> selectCreditConditionByList(List<String> dealerNames)
    {
        return creditConditionMapper.selectCreditConditionByList(dealerNames);
    }
    @Override
    public List<CreditCondition> selectCreditConditionList(CreditCondition creditCondition)
    {
        return creditConditionMapper.selectCreditConditionList(creditCondition);
    }
    /**
     * 新增feike
     *
     * @param creditCondition feike
     * @return 结果
     */
    @Override
    public int insertCreditCondition(CreditCondition creditCondition)
    {
        return creditConditionMapper.insertCreditCondition(creditCondition);
    }

    /**
     * 修改feike
     *
     * @param creditCondition feike
     * @return 结果
     */
    @Override
    public int updateCreditCondition(CreditCondition creditCondition)
    {
        return creditConditionMapper.updateCreditCondition(creditCondition);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteCreditConditionByIds(String[] ids)
    {
        return creditConditionMapper.deleteCreditConditionByIds(ids);
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteCreditConditionById(String id)
    {
        return creditConditionMapper.deleteCreditConditionById(id);
    }

    /**
     * 新增feike
     *
     * @param resultMap
     * @return 结果
     */
    public int saveCreditcs(Map<String, Object> resultMap){
        try {
            List<CreditCondition> hcc = JSONObject.parseArray(JSON.toJSONString(resultMap.get("hcc")), CreditCondition.class);
            String dealerId = (String) resultMap.get("dealerId");
            String dealerName = (String) resultMap.get("dealerName");
            if (StringUtils.isEmpty(hcc)) {
                throw new BaseException("表数据不能为空！");
            }
            for(CreditCondition alacs : hcc ){
                String id = IdUtils.simpleUUID();
                alacs.setId(id);
                alacs.setDealerid(dealerId);
                alacs.setDealername(dealerName);
                creditConditionMapper.insertCreditCondition(alacs);
            }
            return 1;
        }catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.toString());
        }
    }

    @Override
    public List<ThirdCreditInfoSimpleVO> thirdCreditResult(List<String> dealerNames) {
        //根据名称获取code集合
        List<List<String>> dealerIds = this.dealerCodesByNames(dealerNames);
        JSONObject requestParam = new JSONObject();
        requestParam.put("DealerCode",dealerIds);
        String url = wfsUrl+"CreditInfo";;
        //post参数格式： {"DealerCode":[["A89804","K89802"],["M02104","R02104"]]}
        log.info("当前接收参数为：{}",requestParam);
        String response = HttpRequest.post(url)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(requestParam.toString())
                .execute()
                .body();
        JSONObject parse = JSONObject.parseObject(response);
        Integer code = Integer.valueOf(parse.get("Code").toString());
        log.info("当前返回状态码为:{}，消息为：{}",code,parse.get("Message"));
        ThirdCreditInfoVO creditInfoVO = JSON.parseObject(parse.toString(), ThirdCreditInfoVO.class);
        log.info("当前实体对象：{}",creditInfoVO);
        List<ThirdCreditInfoSimpleVO> rs = this.transThirdData(creditInfoVO);
        log.info("当前实体对象2：{}",rs);
        return rs;
    }

    @Override
    public Boolean saveAuditCreditCondition(String instanceId,  List<ThirdCreditInfoSimpleVO> creditList , String title) {

        //先通过instanceID找有没有记录，没有就添加，有则更新
        List<CreditCondition> creditConditions = creditConditionMapper.listByInstanceId(instanceId);
        if(creditConditions != null && creditConditions.size() > 0){
            List<String> ids = creditConditions.stream().map(CreditCondition::getId).collect(Collectors.toList());
            for (String id : ids) {
                CreditCondition creditCondition = creditConditionMapper.selectCreditConditionById(id);
                creditConditionMapper.deleteCreditConditionById(id);
                annualReviewyService.saveDbLog("2",title,"CREDIT CONDITION",instanceId,creditCondition,null,null);
            }

            log.info("删除了{}",ids.size());
        }

//        if(CollectionUtil.isNotEmpty(creditConditions)){ //更新
//           creditList.forEach(e->{
//                e.getChild().forEach(f->{
//                    CreditCondition creditCondition = new CreditCondition();
//                    BeanUtils.copyProperties(f,creditCondition);
//                    creditConditionMapper.updateCreditCondition(creditCondition);
//                });
//            });
//        }else{

            //插入新数据
            log.info("当前creditlist对象{}",creditList);
            for (ThirdCreditInfoSimpleVO creditInfoSimpleVO: creditList){

                for (ThirdCreditInfoSimpleChild child :creditInfoSimpleVO.getChild()){
                    log.info("当前子对象{}",child);
                    CreditCondition creditCondition = new CreditCondition();
                    //BeanUtils.copyProperties(child,creditCondition);
                    creditCondition.setId(IdUtils.simpleUUID());
                    creditCondition.setInstanceid(instanceId);
                    creditCondition.setDealerid(child.getDealerId());
                    creditCondition.setDealername(creditInfoSimpleVO.getDealerName());
                    creditCondition.setSector(child.getSector());
                    creditCondition.setLimittype(child.getLimitType());
                    creditCondition.setExpireddate(child.getExpiryDate());
                    creditCondition.setReviewtype(child.getReviewType());
                    creditCondition.setLoantenor(child.getLoanTenor());
                    creditCondition.setBuyback("N");
                    creditCondition.setInstanceid(instanceId);
                    creditConditionMapper.insertCreditCondition(creditCondition);
                    annualReviewyService.saveDbLog("1",title,"CREDIT CONDITION",instanceId,null,creditCondition,null);
                }
            }
           /* creditList.forEach(e->{
                e.getChild().forEach(f->{
                    CreditCondition creditCondition = new CreditCondition();
                    BeanUtils.copyProperties(f,creditCondition);
                    f.setId(IdUtils.simpleUUID());
                    f.setInstanceId(instanceId);
                    creditConditionMapper.insertCreditCondition(creditCondition);
                });
            });*/
       // }
        return true;
    }

    /**
     * 根据名称返回不重复各家企业的code集合，如 [["A89804","K89802"],["M02104","R02104"]]
     * @param dealerNames
     * @return
     */
    public List<List<String>> dealerCodesByNames(List<String> dealerNames){
        ArrayList<List<String>> outList = new ArrayList<>();
        dealerNames.forEach(n->{
            List<DealerInformation> infoListByDealerName = dealerInformationMapper.codesByDealerNames(n);
            if(CollectionUtil.isNotEmpty(infoListByDealerName)){
                List<String> codes = infoListByDealerName.stream().map(DealerInformation::getDealerCode).collect(Collectors.toList());
                outList.add(codes);
            }
        });
        return outList;
    }

    public List<ThirdCreditInfoSimpleVO> transThirdData(ThirdCreditInfoVO creditInfoVO){
        List<List<ThirdCreditInfoVO.Data>> data = creditInfoVO.getData();
        List<ThirdCreditInfoSimpleVO> resp = new ArrayList<>();
        List<ThirdCreditInfoSimpleVO> response = new ArrayList<>();
        if(Arrays.asList(200,205).contains(creditInfoVO.getCode()) ){ //只受理200.205的状态
            List<String> dealerCodes = new ArrayList<>();
            data.forEach(t->{
                t.forEach(e->{
                    dealerCodes.add(e.getDealerCode());
                });
            });
            //获取公司名称
            List<DealerInformation> infos = dealerInformationMapper.listByCodes(dealerCodes);
            Map<String, String>  nameMap = infos.stream().collect(Collectors.toMap(DealerInformation::getDealerCode, DealerInformation::getDealerName , (value1, value2 ) -> value2));
            Map<String, Long>  nameForId = infos.stream().collect(Collectors.toMap(DealerInformation::getDealerCode, DealerInformation::getId));
            Map<String,List<String>> nameArr = new HashMap<>();
            nameMap.forEach((k,v)->{
                if(!nameArr.containsKey(v)){
                    List<String> cds = new ArrayList<>();
                    nameMap.forEach((code,name)->{
                        if(name.equals(v)){
                            cds.add(code);
                        }
                    });
                    nameArr.put(v,cds);
                }
            });
            for (String nam:nameArr.keySet())
            {
                ThirdCreditInfoSimpleVO crv = new ThirdCreditInfoSimpleVO();
                List<ThirdCreditInfoSimpleChild> thd = new ArrayList<>();
                for (List<ThirdCreditInfoVO.Data> m:data)
                {
                    for (ThirdCreditInfoVO.Data n:m)
                    {
                        if(nameArr.get(nam).contains(n.getDealerCode())){
                            //crv.setDealerId(nameForId.get(code));
                            crv.setDealerName(nam);
                            for (ThirdCreditInfoVO.CreditInfo k:n.getCreditInfo()){

                                for (ThirdCreditInfoVO.CreditDet p:k.getCreditDet())
                                {
                                    ThirdCreditInfoSimpleChild thidinfo = new ThirdCreditInfoSimpleChild();
                                    BeanUtils.copyProperties(p,thidinfo);
                                    if(StringUtils.isNotEmpty(p.getExpiryDate())){
                                        String dt = DateFormatUtils.format(new Date(p.getExpiryDate()), "YYYY-MM-dd");
                                        System.out.println(dt);
                                        if(dt != null){
                                            try {
                                                SimpleDateFormat sp = new SimpleDateFormat("yyyy/MM/dd");
                                                Date parse = sp.parse(p.getExpiryDate());
                                                thidinfo.setExpiryDate(parse);
                                            }catch (ParseException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }
                                    }
                                    thidinfo.setId("");
                                    thidinfo.setInstanceId("");
                                    thidinfo.setReviewType("");
                                    thidinfo.setLoanTenor("");
                                    thidinfo.setBuyBack("");
                                    thidinfo.setSector(k.getSector());
                                    thidinfo.setDealerId(nameArr.get(nam).get(0));
                                    thidinfo.setDealerName(nam);
                                    thd.add(thidinfo);
                                };
                            };
                        }
                    };
                };
                crv.setChild(thd);
                response.add(crv);
            };
        }
        return response;
    }

}
